
const crypto = require('crypto');  
const jwt = require('jsonwebtoken');  
  
module.exports = (app, connection) => {  
  app.post('/register', (req, res) => {  
    const { username, email, password } = req.body;  
  
    connection.query('SELECT * FROM users WHERE username = ? OR email = ?', [username, email], (err, results) => {  
      if (err) {  
        console.error("查询数据表失败：" + err.stack);  
        res.status(500).send("查询数据表失败");  
        return;  
      }  
  
      if (results.length > 0) {  
        res.status(400).send("用户名或电子邮件已被使用");  
        return;  
      }  
  
      // 存储密码哈希值  
      const hash = crypto.createHash('sha256').update(password).digest('hex');  
        
      const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';  
      connection.query(query, [username, email, hash], (err, results) => {  
        if (err) {  
          console.error("插入数据表失败：" + err.stack);  
          res.status(500).send("插入数据表失败");  
          return;  
        }  
        res.json({ message: "注册成功",code: 0 });  
      });  
    });  
  });  
  
  app.post('/login', (req, res) => {  
    const { username, password } = req.body;  
  
    connection.query('SELECT * FROM users WHERE username = ?', [username], (err, results) => {  
      if (err) {  
        console.error("查询数据表失败：" + err.stack);  
        res.status(500).send("查询数据表失败");  
        return;  
      }  
  
      if (results.length === 0) {  
        res.status(400).send("用户名或密码错误");  
        return;  
      }  
  
      const user = results[0];   
      // 哈希用户输入的密码  
      const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');  
      // 比较哈希值是否匹配  
      if (hashedPassword !== user.password) {  
        res.status(400).send("用户名或密码错误");  
        return;  
      }  
  
      jwt.sign({ id: user.id }, 'your_secret_key', { expiresIn: '1h' }, (err, token) => {  
        if (err) {  
          console.error("生成token失败：" + err.stack);  
          res.status(500).send("生成token失败");  
          return;  
        }  
        res.json({ token,code:0 });  
      });  
    });  
  });  
};
